package org.onion.pattern.event.springboot.rocketmq.consume;

import org.onion.pattern.event.springboot.rocketmq.config.RocketMessageMetadata;
import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;


public abstract class RocketMQContextHolder {

    private static final ThreadLocal<RocketMessageMetadata> inheritableHolder = new NamedInheritableThreadLocal("RocketMQ context");
    private static final ThreadLocal<RocketMessageMetadata> holder = new NamedThreadLocal("Request attributes");

    public static void reset() {
//        requestAttributesHolder.remove();
        inheritableHolder.remove();
    }

    public static void setMetadata(@Nullable RocketMessageMetadata metada) {
        setMetadata(metada, false);
    }


    public static void setMetadata(@Nullable RocketMessageMetadata metada, boolean inheritable) {
        if (metada == null) {
            reset();
        } else if (inheritable) {
            inheritableHolder.set(metada);
            holder.remove();
        } else {
            holder.set(metada);
            inheritableHolder.remove();
        }

    }


    @Nullable
    public static RocketMessageMetadata getMetadata() {
        RocketMessageMetadata val = holder.get();
        if (val == null) {
            val = inheritableHolder.get();
        }

        return val;
    }

}
